<template>
	<view class="container">
		<view class="search-box">
			<view class="search-input">
				<text class="iconfont icon-search"></text>
				<input type="text" v-model="searchQuery" placeholder="搜索商品" confirm-type="search" @confirm="handleSearch" />
			</view>
		</view>
		
		<view class="category-content">
			<view class="filter-bar">
				<view class="filter-item" :class="{ active: currentSort === 'default' }" @click="setSort('default')">
					<text>默认</text>
				</view>
				<view class="filter-item" :class="{ active: currentSort === 'sales' }" @click="setSort('sales')">
					<text>销量</text>
				</view>
				<view class="filter-item" :class="{ active: currentSort === 'price' }" @click="setSort('price')">
					<text>价格</text>
					<text class="sort-icon">{{ priceSortIcon }}</text>
				</view>
			</view>
			
			<view class="goods-list">
				<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="goToDetail(item.id)">
					<image :src="getImgUrl(item.image && item.image.length > 0 ? item.image[0] : '')" mode="aspectFill" class="goods-image"></image>
					<view class="goods-info">
						<text class="goods-name">{{ item.name }}</text>
						<text class="goods-price">¥{{ item.price }}</text>
						<view class="goods-footer">
							<text class="goods-sales">销量: {{ item.salesVolume || 0 }}</text>
							<text class="goods-stock" v-if="item.stock">库存: {{ item.stock }}</text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="loading-more" v-if="loading">
				<text>正在加载...</text>
			</view>
			<view class="no-more" v-if="noMore">
				<text>没有更多商品了</text>
			</view>
		</view>
	</view>
</template>

<script>
import http, { SERVER_BASE_URL } from '@/utils/request';

export default {
	data() {
		return {
			searchQuery: '',
			categoryTag: '',
			keyword: '',
			currentSort: 'default',
			priceAsc: true,
			goodsList: [],
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				status: 'ON_SALE',
				categoryTag: null,
				name: ''
			},
			loading: false,
			noMore: false,
			totalCount: 0
		};
	},
	computed: {
		priceSortIcon() {
			return this.priceAsc ? '↑' : '↓';
		}
	},
	onLoad(options) {
		// 处理参数
		if (options.tag) {
			this.categoryTag = decodeURIComponent(options.tag);
			this.queryParams.categoryTag = [this.categoryTag];
		}
		
		if (options.keyword) {
			this.keyword = decodeURIComponent(options.keyword);
			this.searchQuery = this.keyword;
			this.queryParams.name = this.keyword;
		}
		
		// 从本地存储读取搜索关键词
		const searchKeyword = uni.getStorageSync('searchKeyword');
		if (searchKeyword && !this.keyword) {
			this.keyword = searchKeyword;
			this.searchQuery = searchKeyword;
			this.queryParams.name = searchKeyword;
			// 用完后清除，避免影响下次进入
			uni.removeStorageSync('searchKeyword');
		}
		
		// 从本地存储读取分类标签
		const categoryTag = uni.getStorageSync('categoryTag');
		if (categoryTag && !this.categoryTag) {
			// 处理可能是数组或字符串的情况
			if (Array.isArray(categoryTag)) {
				this.categoryTag = categoryTag[0]; // 显示第一个标签作为当前分类
				this.queryParams.categoryTag = categoryTag; // 使用完整标签数组进行查询
			} else {
				this.categoryTag = categoryTag;
				this.queryParams.categoryTag = [categoryTag];
			}
			// 用完后清除，避免影响下次进入
			uni.removeStorageSync('categoryTag');
		}
		
		// 初始化数据
		this.fetchGoodsList();
	},
	onShow() {
		// 每次进入页面时检查存储
		const searchKeyword = uni.getStorageSync('searchKeyword');
		if (searchKeyword) {
			this.keyword = searchKeyword;
			this.searchQuery = searchKeyword;
			this.queryParams.name = searchKeyword;
			uni.removeStorageSync('searchKeyword');
			// 刷新数据
			this.refreshData();
		}
		
		const categoryTag = uni.getStorageSync('categoryTag');
		if (categoryTag) {
			// 处理可能是数组或字符串的情况
			if (Array.isArray(categoryTag)) {
				this.categoryTag = categoryTag[0]; // 显示第一个标签作为当前分类
				this.queryParams.categoryTag = categoryTag; // 使用完整标签数组进行查询
			} else {
				this.categoryTag = categoryTag;
				this.queryParams.categoryTag = [categoryTag];
			}
			uni.removeStorageSync('categoryTag');
			// 刷新数据
			this.refreshData();
		}
	},
	onPullDownRefresh() {
		this.refreshData();
	},
	onReachBottom() {
		this.loadMoreGoods();
	},
	methods: {
		// 获取商品列表
		async fetchGoodsList() {
			if (this.loading || this.noMore) return;
			
			this.loading = true;
			
			try {
				// 自定义请求，确保数组参数被正确传递
				let url = SERVER_BASE_URL + '/commodities/page';
				
				// 构建基本查询参数
				let queryString = `pageNum=${this.queryParams.pageNum}&pageSize=${this.queryParams.pageSize}`;
				
				// 添加状态参数
				if (this.queryParams.status) {
					queryString += `&status=${this.queryParams.status}`;
				}
				
				// 添加名称参数
				if (this.queryParams.name) {
					queryString += `&name=${encodeURIComponent(this.queryParams.name)}`;
				}
				
				// 添加分类标签参数（如果有）
				if (this.queryParams.categoryTag && this.queryParams.categoryTag.length > 0) {
					// 对于每个分类标签，添加一个单独的categoryTag参数
					this.queryParams.categoryTag.forEach(tag => {
						queryString += `&categoryTag=${encodeURIComponent(tag)}`;
					});
					console.log('分类标签:', this.queryParams.categoryTag);
				}

				// 添加排序参数
				if (this.currentSort === 'sales') {
					queryString += `&sortField=salesVolume&sortOrder=desc`;
				} else if (this.currentSort === 'price') {
					queryString += `&sortField=price&sortOrder=${this.priceAsc ? 'asc' : 'desc'}`;
				} else {
					// 默认排序可不传或传默认字段
				}
				
				url += `?${queryString}`;
				console.log('请求URL:', url);
				
				// 使用uni.request直接发送请求
				uni.request({
					url: url,
					method: 'GET',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (response) => {
						console.log('原始响应:', response);
						
						if (response.statusCode === 200) {
							const res = response.data;
							console.log('获取商品结果:', res);
							
							const list = res.list || [];
							this.totalCount = res.total || 0;
							
							if (this.queryParams.pageNum === 1) {
								this.goodsList = list;
							} else {
								this.goodsList = [...this.goodsList, ...list];
							}
							
							// 判断是否还有更多数据
							if (this.goodsList.length >= this.totalCount) {
								this.noMore = true;
							} else {
								this.noMore = false;
							}
						} else {
							uni.showToast({
								title: '获取商品列表失败',
								icon: 'none'
							});
						}
						
						this.loading = false;
						uni.stopPullDownRefresh();
					},
					fail: (error) => {
						console.error('获取商品列表失败', error);
						uni.showToast({
							title: '获取商品列表失败',
							icon: 'none'
						});
						this.loading = false;
						uni.stopPullDownRefresh();
					}
				});
			} catch (error) {
				console.error('获取商品列表失败', error);
				uni.showToast({
					title: '获取商品列表失败',
					icon: 'none'
				});
				this.loading = false;
				uni.stopPullDownRefresh();
			}
		},
		
		// 加载更多商品
		loadMoreGoods() {
			if (this.loading || this.noMore) return;
			
			this.queryParams.pageNum++;
			this.fetchGoodsList();
		},
		
		// 刷新数据
		refreshData() {
			this.queryParams.pageNum = 1;
			this.noMore = false;
			this.fetchGoodsList();
		},
		
		// 处理搜索
		handleSearch() {
			this.keyword = this.searchQuery;
			this.queryParams.name = this.searchQuery;
			this.refreshData();
		},
		
		// 设置排序
		setSort(type) {
			if (type === 'price') {
				if (this.currentSort === 'price') {
					this.priceAsc = !this.priceAsc;
				} else {
					this.priceAsc = true;
				}
			} else {
				this.priceAsc = true; // 切换到销量或默认时重置为升序
			}
			
			this.currentSort = type;
			this.refreshData();
		},
		
		// 跳转到商品详情
		goToDetail(id) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${id}`
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			
			if (url.startsWith('/uploads/')) {
				fullUrl = SERVER_BASE_URL + url;
			}
			
			return fullUrl;
		}
	}
};
</script>

<style>
.container {
	padding-bottom: 20rpx;
	background-color: #f5f5f5;
}

/* 搜索栏样式 */
.search-box {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
}

.search-input {
	display: flex;
	align-items: center;
	height: 70rpx;
	padding: 0 30rpx;
	background-color: #f5f5f5;
	border-radius: 35rpx;
}

.icon-search {
	margin-right: 10rpx;
	font-size: 28rpx;
	color: #999;
}

.search-input input {
	flex: 1;
	height: 70rpx;
	font-size: 28rpx;
}

/* 分类内容样式 */
.category-content {
	padding: 0 20rpx;
}

/* 筛选栏样式 */
.filter-bar {
	display: flex;
	height: 80rpx;
	background-color: #ffffff;
	margin: 20rpx 0;
	border-radius: 12rpx;
}

.filter-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #333;
}

.filter-item.active {
	color: #409EFF;
	font-weight: bold;
}

.sort-icon {
	margin-left: 6rpx;
}

/* 商品列表样式 */
.goods-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}

.goods-item {
	width: 48%;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.goods-image {
	width: 100%;
	height: 300rpx;
}

.goods-info {
	padding: 16rpx;
}

.goods-name {
	display: block;
	font-size: 28rpx;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.goods-price {
	display: block;
	font-size: 32rpx;
	color: #ff6700;
	font-weight: bold;
	margin: 10rpx 0;
}

.goods-footer {
	display: flex;
	justify-content: space-between;
	font-size: 22rpx;
	color: #999;
}

/* 加载更多样式 */
.loading-more, .no-more {
	padding: 20rpx 0;
	text-align: center;
	font-size: 24rpx;
	color: #999;
}
</style> 